import Schemas from '../schemas';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';

const Friends = new Mongo.Collection('friends');

Friends.attachSchema(Schemas.Friend);

if (Meteor.isServer) {
  Meteor.publish('Get.Friend', function(user_id, target_user_id) {
    check(user_id, String);
    check(target_user_id, String);
  
    let selector = {
      user_id: user_id,
      friend_id: target_user_id
    };
    
    return Friends.find(selector);
  });
}

// 目标用户是否是当前用户的好友
const isFriend = (user_id, target_user_id) => {
  check(user_id, String);
  check(target_user_id, String);

  if (Meteor.isClient) {
    Meteor.subscribe('Get.Friend', user_id, target_user_id);
  }

  const results = Friends.find({
    user_id: user_id,
    friend_id: target_user_id
  });

  if (results.count() === 1) {
    return true;
  } else {
    return false;
  }
};

export { Friends, isFriend };